package content.views.works;
import feffects.easing.Quad;
import js.Lib;
import tools.ASprite;
import js.w3c.html5.Core.HTMLVideoElement;
import tools.BoundProvider;

/**
 * ...
 * @author PRASS
 */

class DemoPlayer extends ASprite 
{
	
	public var isOpen				: Bool;
	
	private var _player 			: ASprite;
	private var _playerContainer 	: ASprite;
	private var _closeBt			: CloseButton;
	
	public function new( jq : JQuery ) 
	{
		super(jq);
		setAlpha(0);
		
		var html : String = '<div id="playerContainer"></div><div id="closeButton"><img src="img/elements/close_button.png"/></div>';
		dom.append(html);
		
		_playerContainer 	= new ASprite( new JQuery("#playerContainer") );
		_closeBt 			= new CloseButton( new JQuery("#closeButton") );
		_closeBt.dom.mousedown( function(e) { _close(e);  }  );
	}
	
	public function buildAndPlay( pSrc : String, pWidth : Int = 640, pHeight : Int = 360 ) : Void
	{
		_playerContainer.dom.empty();
		if ( _player != null) _player = null;
		
		var html : String = '<video id="videoElement" class="video-js vjs-default-skin" controls width="' + pWidth + '" height="' + pHeight + '" preload="auto" data-setup="{}">
								<source type="video/mp4" src="demo/'+pSrc+'.mp4">
								<source type="video/ogg" src="demo/'+pSrc+'.ogg">
							</video>';
		
		_playerContainer.dom.append(html);
		_player = new ASprite( new JQuery("#videoElement"));
		
		resize(BoundProvider.winW-316, BoundProvider.winH);
		
		_display();
	}
	
	private function _display() : Void
	{
		visible(true);
		isOpen = true;
		tween(0, setAlpha, 1, 500, Quad.easeInOut);
	}
	
	private function _close(e) : Void
	{
		isOpen = false;
		hide();
	}
	
	public function hide() : Void
	{
		tween(1, setAlpha, 0, 200, Quad.easeInOut, _clear);
	}
	
	private function _clear() : Void
	{
		if (_player == null) return;
		
		untyped _V_("videoElement").addEvent("error", function(e) { return; } );
		untyped _V_("videoElement").pause();
		untyped _V_("videoElement").hide();
		visible(false);
	}
	
	public function resize( w : Int, h : Int ) : Void
	{
		setY(0);
		setX(316);
		
		setWidth(w);
		setHeight(h);
		
		if (_player == null) return;
		
		var px : Float; 
		var py : Float = (h - 360 ) * .5;
		
		if (w < 744)
			px = Math.max( (w - 640 ) * .5,0);
		else
			px = Math.max( -316 + ( (w+316 - 640 ) * .5), 50);
		
		
		_player.setX( cast px );
		_player.setY( cast py );
		
		_closeBt.setX( cast ( px + 640 - 37 ) );
		_closeBt.setY( cast py + 5 );
		
	}
	
}